package cn.wit.summit.chwan.ui.base;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;

import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.ui.activity.SplashActivity;
import cn.wit.summit.chwan.ui.receiver.BroadcastAction;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PermissionManagerUtil;
import cn.wit.summit.chwan.utils.FileUtils;

import java.io.File;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/3/28.
 */

public class PermissionBaseActivity extends BaseAppCompatActivity
        implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private String appRootPath;
    private InstallAppRecver recver;
    private boolean isbackground = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!(mAty instanceof SplashActivity) && PreferenceUtil.getBoolPreferences(this, PreferenceUtil.PRE_PERMSSION_ALL)) {
            checkAllPerm();
            PreferenceUtil.saveBoolPreference(this, PreferenceUtil.PRE_PERMSSION_ALL, false);
        }
        PreferenceUtil.saveBoolPreference(this, PreferenceUtil.PRE_PERMSSION_STORAGE, true);
        PreferenceUtil.saveBoolPreference(this, PreferenceUtil.PRE_PERMSSION_INSTALL, true);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastAction.ACTION_CHECKANDREQUEST_PERMISS);
        filter.addAction(BroadcastAction.ACTION_INSTALL_APK);
        filter.addAction(BroadcastAction.ACTION_INSTALL_OBB_DATA_APK);
        filter.addAction(BroadcastAction.ACTION_SHOW_NOT_WIFI);
        recver = new InstallAppRecver();
        registerReceiver(recver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isbackground = false;
        getUserinfo();
    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(mAty)) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    RetrofitManager retrofitManager = RetrofitManager.getInstance(mAty);
                    Retrofit retrofitLogin = retrofitManager.getLoginRetrofit();
                    ApiUtil apiLogin = retrofitLogin.create(ApiUtil.class);
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(mAty);
                            }
                            ToastUtils.getInstance(mAty).showToastSystem(msg);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isbackground = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(recver);
    }

    class InstallAppRecver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, Intent intent) {
            if (BroadcastAction.ACTION_SHOW_NOT_WIFI.equals(intent.getAction())) {
                final DownLoadTaskTable taskTable = (DownLoadTaskTable) intent.getSerializableExtra("showNotWifitodownTask");
                DownloadTool.startDownRealy(context, taskTable, false, null);
//                Dialog dialog = new NoticeDialog(context, R.style.NoticeDialogTheme)
//                        .setData("提示", "当前网络为非WIFI网络是否继续下载")
//                        .setOnClickButnInterface(new NoticeDialog.OnClickButnInterface() {
//                            @Override
//                            public void onClickCancleButn(NoticeDialog noticeDialog) {
//                                noticeDialog.dismiss();
//                            }
//
//                            @Override
//                            public void onClickOkButn(NoticeDialog noticeDialog) {
//                                DownloadTool.startDownRealy(context, taskTable);
//                                noticeDialog.dismiss();
//                            }
//                        });
//                if (!isbackground)
//                    dialog.show();
            } else if (BroadcastAction.ACTION_CHECKANDREQUEST_PERMISS.equals(intent.getAction())) {
                PreferenceUtil.saveBoolPreference(PermissionBaseActivity.this, PreferenceUtil.PRE_PERMSSION_STORAGE, true);
                checkStoragePerm();
            } else if (BroadcastAction.ACTION_INSTALL_APK.equals(intent.getAction())) {
                PreferenceUtil.saveBoolPreference(PermissionBaseActivity.this, PreferenceUtil.PRE_PERMSSION_INSTALL, true);
                checkIntallPerm();
            } else if (BroadcastAction.ACTION_INSTALL_OBB_DATA_APK.equals(intent.getAction())) {
                String path = intent.getStringExtra("apkpath");
                String gameId = intent.getStringExtra("apkGameId");

                boolean haveInstallPermission;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //先获取是否有安装未知来源应用的权限
                    haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                    haveInstallPermission = true;
                    if (!haveInstallPermission) {//没有权限
                        if (builder == null) {
                            builder = new AlertDialog.Builder(context);
                            builder.setTitle("权限提示");
                            builder.setMessage("安装应用需要打开未知来源权限，请去设置中开启权限");
                            builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                        startInstallPermissionSettingActivity();
                                    }
                                    dialog.dismiss();
                                    builder = null;
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    builder = null;
                                }
                            });
                            if (!isbackground)
                                builder.show();
                        }else {
                            builder.show();
                        }
                        return;
                    } else {
                        if (StringUtils.isNotEmpty(path))
                            APKUtils.getInstance(context).installAPK(context, path, gameId);
                        return;
                    }
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (PermissionManagerUtil.hasInstallPermission(context)) {
                        APKUtils.getInstance(context).installAPK(context, path, gameId);
                    } else {
                        // Ask for one permission
                        EasyPermissions.requestPermissions(
                                PermissionBaseActivity.this,
                                getString(R.string.rationale_init_install_contacts),
                                PermissionManagerUtil.RC_INSTALL_PERM,
                                PermissionManagerUtil.PERM_INSTALL);
                    }
                }
            }
        }
    }

    @AfterPermissionGranted(PermissionManagerUtil.RC_ALL_PERM)
    public void checkAllPerm() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PermissionManagerUtil.hasAllPermission(this)) {
                initPath();
            } else {
                // Ask for one permission
                EasyPermissions.requestPermissions(
                        this,
                        getString(R.string.rationale_init_all_contacts),
                        PermissionManagerUtil.RC_ALL_PERM,
                        PermissionManagerUtil.PERM_ALL);
            }
        } else {
            initPath();
        }
    }

    @AfterPermissionGranted(PermissionManagerUtil.RC_STORAGE_PERM)
    private void checkStoragePerm() {
        LogUtils.e("tbl>>>checkStoragePerm:");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PermissionManagerUtil.hasStoragePermission(this)) {
                initPath();
            } else {
                // Ask for one permission
                EasyPermissions.requestPermissions(
                        this,
                        getString(R.string.rationale_init_storage_contacts),
                        PermissionManagerUtil.RC_STORAGE_PERM,
                        PermissionManagerUtil.PERM_STORAGE);
            }
        } else {
            initPath();
        }

    }

    AlertDialog.Builder builder;

    @AfterPermissionGranted(PermissionManagerUtil.RC_INSTALL_PERM)
    private void checkIntallPerm() {
        LogUtils.e("tbl>>>checkIntallPerm:");
        boolean haveInstallPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            haveInstallPermission = true;
            if (!haveInstallPermission) {//没有权限
                if (builder == null) {
                    builder = new AlertDialog.Builder(this);
                    builder.setTitle("权限提示");
                    builder.setMessage("安装应用需要打开未知来源权限，请去设置中开启权限");
                    builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                startInstallPermissionSettingActivity();
                            }
                            dialog.dismiss();
                            builder = null;
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            builder = null;
                        }
                    });

                    if (!isbackground)
                        builder.show();
                }else {
                    builder.show();
                }
                return;
            } else {

            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PermissionManagerUtil.hasInstallPermission(this)) {
                initPath();
            } else {
                // Ask for one permission
                EasyPermissions.requestPermissions(
                        this,
                        getString(R.string.rationale_init_install_contacts),
                        PermissionManagerUtil.RC_INSTALL_PERM,
                        PermissionManagerUtil.PERM_INSTALL);
            }
        } else {
            initPath();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
//        //注意这个是8.0新API
//        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
//        startActivityForResult(intent, 10086);

        Uri packageURI = Uri.parse("package:" + this.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 10086);
    }

    public void initPath() {
        String dbName = MyApplication.getMyApplication().getDbName();
        appRootPath = FileUtils.SDPATH + dbName + "/";
        File file = new File(FileUtils.SDPATH, dbName);
        LogUtils.e("tbl>>>appRootPath:" + file.getPath());
        LogUtils.e("tbl>>>file.exists():" + file.exists());
        if (!file.exists()) {
            boolean bs = file.mkdirs();
            LogUtils.e("tbl>>>file.mkdirs():" + bs);
            if (!bs) {
                FileUtils.initPath(this);
                initPath();
            } else {
                MyApplication.getMyApplication().setAppRootPath(appRootPath);
            }
        } else {
            MyApplication.getMyApplication().setAppRootPath(appRootPath);
        }
    }

    /**
     * 授权成功
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        LogUtils.e("tbl>>>onPermissionsGranted:" + requestCode + ":" + perms.size());
//        checkPermByCode(requestCode);
    }

    /**
     * 授权失败
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        LogUtils.e("tbl>>>onPermissionsDenied:" + requestCode + ":" + perms.size());
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            //已经拒绝权限授权后，要跳转去系统设置当前app的权限
            LogUtils.e("tbl>>>AppSettingsDialog:");
            if (requestCode == PermissionManagerUtil.RC_STORAGE_PERM) {
                if (PreferenceUtil.getBoolPreferences(this, PreferenceUtil.PRE_PERMSSION_STORAGE)) {
                    PreferenceUtil.saveBoolPreference(this, PreferenceUtil.PRE_PERMSSION_STORAGE, false);
                    new AppSettingsDialog.Builder(this).setTitle("注意").setRationale(R.string.rationale_init_storage_contacts).build().show();
                }
            }
            if (requestCode == PermissionManagerUtil.RC_INSTALL_PERM) {
                if (PreferenceUtil.getBoolPreferences(this, PreferenceUtil.PRE_PERMSSION_INSTALL)) {
                    PreferenceUtil.saveBoolPreference(this, PreferenceUtil.PRE_PERMSSION_INSTALL, false);
                    new AppSettingsDialog.Builder(this).setTitle("注意").setRationale(R.string.rationale_init_install_contacts).build().show();
                }
            }
        } else {
//            checkPermByCode(requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LogUtils.e("tbl>>>onRequestPermissionsResult:");
        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.e("tbl>>>onActivityResult:");
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            // Do something after user returned from app settings screen, like showing a Toast.
            checkStoragePerm();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        LogUtils.e("tbl>>>onRationaleAccepted:" + requestCode);
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        LogUtils.e("tbl>>>onRationaleDenied:" + requestCode);
        checkPermByCode(requestCode);
    }

    private void checkPermByCode(int requestCode) {
        switch (requestCode) {
            case PermissionManagerUtil.RC_INSTALL_PERM://安装
                checkAllPerm();
                break;
            case PermissionManagerUtil.RC_STORAGE_PERM://读写手机内存
                checkStoragePerm();
                break;
        }
    }
}
